<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--组织数据-->
      <el-col :span="device=='pc'?4:7" :xs="24">
        <div class="head-container">
          <el-input
            v-model="deptName"
            placeholder="请输入组织名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container head-tree">
          <el-tree
            :data="deptOptions"
            :props="{ label: 'deptName', children: 'children' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            :current-node-key="currentKey"
            ref="deptTreeRef"
            node-key="deptCode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          />
        </div>
      </el-col>
      <!--日历数据-->
      <el-col :span="device=='pc'?20:17" :xs="24" v-loading="loadingCla">
        <el-calendar v-model="nowDate">
          <template #date-cell="{ data }">
            <div
              :class="['day-content', { 'pass-time': isDisabled(data) }]"
              @click.stop="showDetail(data)"
            >
              <div style="display: flex; justify-content: space-between">
                <span class="day">{{ data.day.split("-")[2] }}</span>
                <span
                  v-if="statusData[data.day] == 'ON'"
                  class="status"
                  size="mini"
                  >班</span
                >
                <span
                  v-else-if="statusData[data.day] == 'NOT'"
                  class="status off-work"
                  size="mini"
                  >班/休</span
                >
                <span
                  v-else-if="statusData[data.day] == 'OFF'"
                  class="status off-work"
                  size="mini"
                  >休</span
                >
              </div>

              <div v-if="dateData[data.day]?.scheduleCalendarList">
                <div
                  v-for="(item, index) in dateData[data.day]
                    .scheduleCalendarList"
                  :key="index"
                >
                  <div
                    class="itemScheduleName"
                    v-if="item.workGroupName"
                    :class="
                      item.scheduleName == '中班'
                        ? 'Bday'
                        : item.scheduleName == '晚班'
                        ? 'Cday'
                        : ''
                    "
                  >
                    <i class="sunrise-1"></i>
                    {{ item.workGroupName }}
                  </div>
                </div>
              </div>
            </div>
          </template>
        </el-calendar>
      </el-col>
    </el-row>
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog
      :title="'排班'"
      :close-on-click-modal="false"
      v-model="open"
      width="800px"
      append-to-body
    >
      <div style="height: 40px; font-size: 15px">
        <span style="margin-right: 20px">{{ digTitle.date }}</span>
        <span>{{ digTitle.factoryObj[0] }}-</span>
        <span>{{ digTitle.factoryObj[1] }}-</span>
        <span>{{ digTitle.factoryObj[2] }}-</span>
        <span>{{ digTitle.factoryObj[3] }}</span>
      </div>
      <el-table
        v-loading="loading"
        border
        :data="typeList"
        :span-method="arraySpanMethod"
      >
        <el-table-column label="班次" align="center" prop="scheduleName" />
        <el-table-column label="开始时间" align="center" prop="startTime" />
        <el-table-column label="结束时间" align="center" prop="endTime" />
        <el-table-column label="班组" align="center" prop="workGroupName" />
        <el-table-column label="班长" align="center" prop="monitorName" />
        <el-table-column
          label="班组成员"
          align="center"
          prop="workStationStaff"
        />
      </el-table>
      <!-- <p v-if="!typeList.length" style="color: red;">【全天休息/尚未排班】</p> -->
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup name="WorkdaySetting">
import { queryList } from "@/api/base/plan/shiftMgt/shiftCalendar";
import {
  addWorkday,
  updateWorkday,
  listWorkday,
  delWorkday,
  getWorkday,
} from "@/api/base/plan/shiftMgt/workdaySetting";
import { getFactoryTree } from "@/api/system/dept";

const { proxy } = getCurrentInstance();
const weekStr = ["日", "一", "二", "三", "四", "五", "六"];

var currentArrCode = ref([]);
var currentArrName = ref([]);
const deptName = ref("");
const currentKey = ref("");
const open = ref(false);
const typeList = ref([]);
const digTitle = ref([]);
const loading = ref(false);
const deptOptions = ref(undefined);
const currentDate = ref({});
const nowDate = ref(new Date());
const dateData = ref({});
const statusData = ref({});
const newDateTime = new Date().setHours(0, 0, 0, 0);
const weekdayDialog = ref(false);
const loadingCla = ref(false);
const device = ref(localStorage.getItem("device"));
const data = reactive({
  form: {},
  queryParams: {
    factory: "",
    dept: "",
    workshopCode: "",
    sectionCode: "",
    productLine: "",
    yearStr: new Date().getFullYear(),
    monthStr:
      new Date().getMonth() + 1 > 9
        ? new Date().getMonth() + 1
        : "0" + (new Date().getMonth() + 1),
  },
});

const { queryParams } = toRefs(data);

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.deptName.indexOf(value) !== -1;
};
/** 根据名称筛选组织树 */
watch(deptName, (val) => {
  proxy.$refs["deptTreeRef"].filter(val);
});
/**  */
watch(nowDate, (val) => {
  // 中国标准时间
  let date1 = val;
  // 年
  let y = date1.getFullYear();
  // 月
  let m = date1.getMonth() + 1;
  m = m < 10 ? "0" + m : m;
  // 日
  let d = date1.getDate();
  d = d < 10 ? "0" + d : d;
  // 时
  let h = date1.getHours();
  h = h < 10 ? "0" + h : h;
  // 分
  let M = date1.getMinutes();
  M = M < 10 ? "0" + M : M;
  // 秒
  let s = date1.getSeconds();
  s = s < 10 ? "0" + s : s;
  let dateTime = y + "-" + m + "-" + d + " " + h + ":" + M + ":" + s;
  queryParams.value.yearStr = y;
  queryParams.value.monthStr = m;
  getList();
});

onDeactivated(() => {
  getList();
});

function getFactorys() {
  getFactoryTree().then((res) => {
    deptOptions.value = res.data;
    currentKey.value = deptOptions.value[0].children[0].children[0].deptCode;
    currentArrName.value = [
      deptOptions.value[0].deptName,
      deptOptions.value[0].children[0].deptName,
      deptOptions.value[0].children[0].children[0].deptName,
      deptOptions.value[0].children[0].children[0].children[0].deptName,
    ];
    currentArrCode = [
      deptOptions.value[0].deptCode,
      deptOptions.value[0].children[0].deptCode,
      deptOptions.value[0].children[0].children[0].deptCode,
      deptOptions.value[0].children[0].children[0].children[0].deptCode,
    ];
    nextTick(() => {
      proxy.$refs["deptTreeRef"].setCurrentKey(
        deptOptions.value[0].children[0].children[0].children[0].deptCode
      );
      getList(currentArrCode);
    });
  });
}

function arraySpanMethod({ row, column, rowIndex, columnIndex }) {
  if (!row.workGroupName) {
    row.startTime = "休息";
    if (columnIndex === 1) {
      return [1, 5];
    }
  }
}

function isDisabled(date) {
  let _day = date.day;
  return new Date(_day).getTime() < newDateTime;
}

/** 节点单击事件 */
function handleNodeClick(data, node, self) {
  currentArrCode = findParent(deptOptions.value, data.deptCode, "deptCode")
    .reverse()
    .concat(data.deptCode);
  currentArrName.value = findParent(
    deptOptions.value,
    data.deptCode,
    "deptName"
  )
    .reverse()
    .concat(data.deptName);
  queryParams.value.factory = currentArrCode[0] || "";
  queryParams.value.workshopCode = currentArrCode[1] || "";
  queryParams.value.productLine = currentArrCode[2] || "";
  queryParams.value.sectionCode = currentArrCode[3] || "";
  // 只有点到工艺段的时候采取调接口
  if (queryParams.value.sectionCode) {
    getList();
  }
}
function findParent(dataSource, nodeId, type) {
  const parentIds = []; // 用于存储所有父节点ID的数组 // 定义一个递归函数，用于遍历整棵树并查找子节点的所有父节点
  function traverse(node, nodeId) {
    if (node.deptCode === nodeId) {
      // 如果当前节点的ID等于子节点的ID，则表示已经找到了子节点，可以开始向上查找父节点
      return true; // 返回true表示已经找到了子节点
    }
    if (node.children) {
      // 如果当前节点有子节点，则继续遍历子节点
      for (const childNode of node.children) {
        if (traverse(childNode, nodeId)) {
          // 如果在子节点中找到了子节点的父节点，则将当前节点的ID添加到父节点ID数组中，并返回true表示已经找到了子节点
          parentIds.push(node[type]);
          return true;
        }
      }
    }
    return false; // 如果当前节点不是子节点的父节点，则返回false
  } // 从根节点开始遍历整棵树，并调用递归函数查找子节点的所有父节点
  for (const node of dataSource) {
    if (traverse(node, nodeId)) {
      // 如果在当前节点的子树中找到了子节点的父节点，则直接退出循环
      break;
    }
  }
  return parentIds; // 返回所有父节点ID的数组
}
function isExistRest(value, index, ar) {
  if (value?.produceStatus == "ON") {
    return true;
  } else {
    return false;
  }
}

function showDetail(data) {
  digTitle.value.date = data.day + " " + "星期" + weekStr[data.date.getDay()];
  digTitle.value.factoryObj = currentArrName.value;
  typeList.value = dateData.value[data.day]?.scheduleCalendarList || [];
  open.value = true;
}

function getList(currentArrCode) {
  dateData.value = {}
  weekdayDialog.value = false;
  loadingCla.value = true;
  if (currentArrCode?.length) {
    queryParams.value.factory = currentArrCode[0];
    queryParams.value.workshopCode = currentArrCode[1];
    queryParams.value.productLine = currentArrCode[2];
    queryParams.value.sectionCode = currentArrCode[3];
  }
  const { factory, workshopCode, productLine, sectionCode, yearStr, monthStr } =
    queryParams.value;
  const params = {
    factory,
    workshopCode,
    productLine,
    sectionCode,
    yearStr,
    monthStr,
  };
  queryList(params)
    .then((res) => {
      loadingCla.value = false;
      if (res.code == 200) {
        if (res?.data) {
          const dataList = res.data;
          for (let key in dataList) {
            let _day =
              dataList[key].dayNo > 9
                ? dataList[key].dayNo
                : "0" + dataList[key].dayNo;
            let _date =
              queryParams.value.yearStr +
              "-" +
              queryParams.value.monthStr +
              "-" +
              _day +
              "";
            dateData.value[_date] = dataList[key];
          }
        } else {
          dateData.value = {};
        }
      }
    })
    .catch(() => {});
  listWorkday(params)
    .then((res) => {
      if (res.code == 200) {
        const dataList = res.data;
        let classesDutyList = [];
        for (let key in dataList) {
          let day = key > 9 ? key : "0" + key;
          let dataKey =
            queryParams.value.yearStr +
            "-" +
            queryParams.value.monthStr +
            "-" +
            day +
            "";
          if (dataList[key]) {
            classesDutyList = dataList[key]?.classesDutyList;
            if (classesDutyList?.length) {
              //工厂，车间，产线，工艺段四个层级数据
              let lineList = [];
              classesDutyList.forEach((ele, index) => {
                if (ele?.workshopDutyInfoList?.length) {
                  ele.workshopDutyInfoList.forEach((item) => {
                    if (item?.lineDutyInfoList?.length) {
                      item.lineDutyInfoList.forEach((tar) => {
                        if (tar?.sectionDutyInfoDtoList?.length) {
                          tar.sectionDutyInfoDtoList.forEach((ts) => {
                            lineList.push({
                              produceStatus: ts.produceStatus,
                            });
                            currentDate.value[dataKey] = lineList;
                          });
                        } else {
                          lineList.push({
                            produceStatus: "ON",
                          });
                          currentDate.value[dataKey] = lineList;
                        }
                      });
                    } else {
                      lineList.push({
                        produceStatus: "ON",
                      });
                      currentDate.value[dataKey] = lineList;
                    }
                  });
                } else {
                  lineList.push({
                    produceStatus: "ON",
                  });
                  currentDate.value[dataKey] = lineList;
                }
              });

              for (let idx in currentDate.value) {
                if (currentDate.value[idx].every(isExistRest)) {
                  //所有产线都是工作日
                  statusData.value[idx] = "ON";
                } else {
                  if (!currentDate.value[idx].some(isExistRest)) {
                    //都是休息日
                    statusData.value[idx] = "OFF";
                  } else {
                    statusData.value[idx] = "NOT";
                  }
                }
              }
            }
          } else {
            //没有配置休息和工作日
            nextTick(() => {
              statusData.value[dataKey] = "ON";
            });
          }
        }
        console.log(statusData.value);
      }
    })
    .catch(() => {});
}

getFactorys();
</script>
<style lang="scss" scoped>
.head-tree {
  height: 710px;
  overflow: auto;
}
:deep(.el-calendar-table) {
  thead th::before {
    content: "星期";
  }
  td.is-selected {
    background: none;
  }
  td.is-today {
    color: inherit;
  }
  .el-calendar-day {
    padding: 0;
    &:hover {
      background: none;
      cursor: pointer;
    }
  }
}

.day-content {
  width: 100%;
  height: 100%;
  padding: 16px;
  .day {
    display: inline-block;
    vertical-align: middle;
    width: 50px;
    height: 34px;
    line-height: 34px;
    text-align: center;
  }
  .status {
    display: inline-block;
    vertical-align: middle;
    width: 36px;
    height: 20px;
    line-height: 20px;
    text-align: center;
    border-radius: 6px;
    font-size: 12px;
    background: #88c446;
    color: #ffffff;
    cursor: pointer;
    &.off-work {
      background: #f56c6c;
    }
  }
  &.pass-time {
    background-color: #f5f5f5;
    .status {
      opacity: 0.75;
    }
  }
  .itemScheduleName {
    text-align: center;
    height: 24px;
    line-height: 24px;
    width: 100%;
    background-color: #88c446;
    margin-bottom: 5px;
    color: #fff;
    font-size: 14px;
  }
  .Bday {
    background-color: #ce6b09;
  }
  .Cday {
    background-color: #ccc;
  }
}

:deep(.el-calendar-table):not(.is-range) td.prev,
:deep(.el-calendar-table):not(.is-range) td.next {
  cursor: not-allowed;
  pointer-events: none;
}
.prev > .el-calendar-day > p {
  display: none;
}
.next > .el-calendar-day > p {
  display: none;
}
:deep .el-calendar-table .el-calendar-day {
  // box-sizing: border-box;
  // padding: 8px;
  height: var(--el-calendar-cell-width);
  height: 130px !important;
}
:deep .el-calendar-table td {
  height: 130px !important;
  border-bottom: var(--el-calendar-border);
  border-right: var(--el-calendar-border);
  vertical-align: top;
  transition: background-color var(--el-transition-duration-fast) ease;
}
</style>
